package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpReceiver {
    public static void main(String[] args) {
        //声明数据报
        DatagramPacket dp = null;
        //声明数据包套接字
        DatagramSocket ds = null;
        Scanner input = new Scanner(System.in);
        try {
            ds = new DatagramSocket(8989);
            byte [] data = new byte[1024];
            while(true){
                dp= new DatagramPacket(data,data.length);
                //接受发送方发送过来的数据包
                ds.receive(dp);//阻塞数据直到，有客户端发送数来
                String info = new String(dp.getData(),0,dp.getLength());
                /*if (info.equals("bye")) {
                    break;
                }*/
                InetAddress ia = dp.getAddress();//指发送方发的地址
                System.out.println(ia.getHostAddress() + ":" + dp.getPort() + "说：" + info);
                info = input.nextLine();
                byte[] buf = info.getBytes();
                dp = new DatagramPacket(buf,buf.length,dp.getSocketAddress());//getSocketAddress客户端的IP
                ds.send(dp);
            }

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }
    }
}
